<script setup lang="ts">
import { computed, ref } from "vue";
import { clipboard } from "@electron/remote";
import { CopyDocument, UserFilled } from "@element-plus/icons-vue";
import { PlanetUtils } from "../../repositories/plants/utils/PlanetUtils";
import type { PlanetProduct } from "../../repositories/plants/entity/PlanetProduct";
import type { PlayerPlanet } from "../../repositories/plants/entity/PlayerPlanet";
import type { TreeInstance } from "@chulei-ui/element-plus";
import type { Role } from "../../repositories/role/entity";
import UniverseTypeIcon from "~components/universe-type/UniverseTypeIcon.vue";
import Segment from "~components/segment/Segment.vue";

const props = defineProps<{ players?: Role[] }>();
const treeRef = ref<TreeInstance>();
const playerTree = computed(() => {
  if (!props.players?.length) {
    return [];
  }
  return props.players?.map((player) => {
    return {
      label: player.name,
      value: player.id,
      type: "player",
      disabled: true,
      children: player.planets?.map((planet) => {
        const { totalInputStatistics, totalOutputStatistics } = planet.statistics;
        return {
          label: `${planet.name} ${planet.system.name}-${planet.system.security_status}`,
          value: planet.id,
          typeId: planet.type.id,
          type: "planet",
          planet,
          children: [
            {
              value: "inputs",
              label: "输入",
              type: "inputs",
              disabled: true,
              planet,
              children: totalInputStatistics.map((input) => {
                return {
                  typeId: input.id,
                  label: input.name,
                  value: `${planet.id}_${input.id}`,
                  cycleCount: input.cycleCount,
                  type: "resources",
                  disabled: true,
                };
              }),
            },
            {
              label: "输出",
              value: "outputs",
              type: "outputs",
              disabled: true,
              children: totalOutputStatistics.map((output) => {
                return {
                  typeId: output.id,
                  label: output.name,
                  value: `${planet.id}_${output.id}`,
                  cycleCount: output.cycleCount,
                  type: "resources",
                  disabled: true,
                };
              }),
            },
          ],
        };
      }),
    };
  });
});

const planets = ref<PlayerPlanet[]>([]);
const factories = computed(() => {
  return planets.value.flatMap((planet) => planet.factories);
});

const originalSource = computed(() => {
  return PlanetUtils.accumulatePlanetProduct(planets.value.flatMap((planet) => planet.basicResource));
});
const inputs = computed(() => {
  return PlanetUtils.getTotalInputStatistics(factories.value, originalSource.value).filter(
    (input) => input.cycleCount! !== 0
  );
});

const outputs = computed(() => {
  return PlanetUtils.getTotalOutputStatistics(factories.value);
});

const getTotalVolume = (products?: PlanetProduct[]) => {
  if (!products) {
    return 0;
  }
  return Math.ceil(products.reduce((total, product) => total + (product.volume ?? 0), 0));
};

/**
 * 复制清单
 * @param products
 */
const copyDetails = (products: PlanetProduct[]) => {
  const texts = [`输入体积: ${getTotalVolume(products)}m³`];
  products.forEach((product) => {
    texts.push(`${product.name}: ${product.count}个(${product.volume})m³`);
  });
  clipboard.writeText(texts.join("\n"));
};
const onCheckedChange = () => {
  planets.value = treeRef.value!.getCheckedNodes().flatMap((node) => node.planet);
};
</script>

<template>
  <div v-if="players?.length">
    <el-divider>个人星球</el-divider>
    <el-row>
      <el-col :span="12">
        <el-tree
          ref="treeRef"
          class="planet-tree"
          check-strictly
          :data="playerTree"
          show-checkbox
          @check-change="onCheckedChange"
        >
          <template #default="{ data }">
            <div v-if="data.type === 'player'" class="flex items-center space-x-2 justify-center">
              <el-icon>
                <UserFilled />
              </el-icon>
              <span>
                {{ data.label }}
              </span>
            </div>
            <div v-if="data.type === 'planet'" class="flex items-center space-x-2 justify-center">
              <UniverseTypeIcon :id="data.typeId" />
              <span>
                {{ data.label }}
              </span>
            </div>
            <div
              v-if="data.type === 'inputs' || data.type === 'outputs'"
              class="flex items-center space-x-2 justify-center"
            >
              <span :class="data.type === 'inputs' ? 'text-green-500' : 'text-blue-500'">
                <el-popover
                  ref="popover"
                  placement="right"
                  :title="`添料表${getTotalVolume(data.planet?.launchCenterDetails)}`"
                  :width="270"
                  trigger="contextmenu"
                >
                  <div v-if="data.planet" class="space-y-1">
                    <div v-for="product in data.planet.launchCenterDetails" :key="product.id" class="flex space-x-2">
                      <UniverseTypeIcon :id="product.id" />
                      <span>{{ product.name }}</span>
                      <span>{{ product.count }}/{{ product.volume }}m³</span>
                    </div>
                  </div>
                  <template #reference>
                    <div class="flex items-center space-x-2">
                      <el-tooltip
                        v-if="data.type === 'inputs' && data.planet?.launchCenterDetails.length > 0"
                        content="复制配料清单"
                      >
                        <el-icon @click.stop="() => copyDetails(data.planet.launchCenterDetails)">
                          <CopyDocument />
                        </el-icon>
                      </el-tooltip>
                      <span>{{ data.label }}</span>
                    </div>
                  </template>
                </el-popover>
              </span>
            </div>
            <div v-if="data.type === 'resources'" class="flex items-center space-x-2 justify-center">
              <UniverseTypeIcon :id="data.typeId" />
              <span>
                {{ data.label }}
                <span :class="data.cycleCount < 0 ? 'text-red-500' : ''">{{ data.cycleCount }}/30分钟</span>
              </span>
            </div>
          </template>
        </el-tree>
      </el-col>
      <el-col :span="12">
        <el-row :gutter="12">
          <el-col :span="12">
            <Segment border>
              <template #header>输入负载</template>
              <el-scrollbar :max-height="500">
                <div v-for="input in inputs" :key="input.id" class="flex space-x-2 text-sm">
                  <UniverseTypeIcon :id="input.id" />
                  <span :class="input.cycleCount! >=0 ? '' : 'text-red-500'"
                    >{{ input.name }} {{ input.cycleCount }}/30分钟</span
                  >
                </div>
              </el-scrollbar>
            </Segment>
          </el-col>
          <el-col :span="12">
            <Segment border>
              <template #header>输出产物</template>
              <el-scrollbar :max-height="500">
                <div v-for="output in outputs" :key="output.id" class="flex space-x-2 text-sm">
                  <UniverseTypeIcon :id="output.id" />
                  <span>{{ output.name }} {{ output.cycleCount }}/30分钟</span>
                </div>
              </el-scrollbar>
            </Segment>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>
<style lang="scss">
.planet-tree {
  .el-checkbox.is-disabled {
    display: none;
  }
}
</style>
